import React, { useEffect, useRef, useState } from 'react'

import { Button, Switch, message } from 'antd'

import defaultAvatar from '../../assets/img/avatar.png'

import Emoji from '../emoji/emoji'

import './form.scss'

import {
  GetQQInfo,
  GetRandomAvatar,
  UserAuthentication,
  UserLogin,
  UserLogout,
} from '../../api/user'

import storage from '../../utils/storage'
import { DeleteComment, GetComments, InsertComment } from '../../api/comment'

import List from '../list'

interface IProps {
  userinfo: any
  login: Function
  logout: Function
}

message.config({
  maxCount: 2,
})

function form(props: IProps) {
  const [comments, setComments] = useState<any[]>([]) // 留言列表
  const [loginState, setLoginState] = useState(false) // 登录状态
  const [isLoging, setIsLoging] = useState(false) // 登录加载
  const [secret, setSecret] = useState(false) // 悄悄话开关
  const [avatar, setAvatar] = useState(false) // 加载头像开关

  // 分页
  const [current, setCurrent] = useState(0)
  const [pagesize, setPagesize] = useState<number | undefined>(5)
  const [total, setTotal] = useState(100)

  // const [submitTriggle, setSubmitTriggle] = useState(false) // 提交加载
  const [formFields, setFormFields] = useState({
    qq: '', // qq
    avatar: '', // 头像
    nickname: '', // 昵称
    email: '', // 邮箱
    weburl: '', // 网站
  })
  const [userid, setUserid] = useState('') // 用户ID
  const [replyId, setReplyId] = useState('') // 回复留言ID
  const [comment, setComment] = useState('') // 留言内容
  const [placeholder, setPlaceholder] = useState('请输入评论内容...') // 留言ID
  const [at, setAt] = useState('') // @
  const [scrollY, setScrollY] = useState(0) // 评论后跳转到当前评论位置
  useEffect(() => {
    init()
  }, [])

  const init = () => {
    autoLogin()
    fetchComment(current, pagesize)
  }

  const textArea: any = useRef() // TextArea Dom

  // 获取留言列表
  const fetchComment = async (page?: number, pageSize?: number) => {
    const { comments, count } = (await GetComments(page, pageSize)) as any
    setComments(comments)
    setTotal(count)
  }

  // 文本框改变事件
  const handelInput = (e: any) => {
    let key = e.target.name
    let value = e.target.value
    setFormFields((prevState: any) => {
      return { ...prevState, [key]: value }
    })
  }

  // 文本框失去焦点
  const handelInputBlur = (e: any) => {
    let qq = e.target.value
    if (!qq) return
    let regex = new RegExp(/^[1-9]*[1-9][0-9]*$/)
    if (regex.test(qq)) {
      GetQQInfo(qq).then((res) => {
        setFormFields((prevState: any) => {
          return {
            ...prevState,
            nickname: res.nick,
            avatar: res.pic,
            email: `${res.qq}@qq.com`,
          }
        })
      })
    }
  }

  const handelTextAreaInput = (e: any) => {
    setComment(e.target.value)
  }

  // 表情选择
  const handelEmojiChose = (emoji: string) => {
    setComment((prevState: string) => {
      return prevState + emoji + '  '
    })
  }

  // 悄悄话开关
  const handelSwitchChange = (trigger: boolean) => setSecret(trigger) // 秘密留言开关

  // ajax

  // 登录
  const login = async () => {
    setIsLoging(true) // 加载开始
    const { nickname, qq, email, weburl, avatar } = formFields

    if (!nickname || (!nickname && !email)) {
      message.warn('昵称和邮箱必填哦!')
      setIsLoging(false)
      return
    }

    if (!avatar) {
      // 获取随机头像
      getAvatar()
    }

    // 非空
    if (nickname && email) {
      const {
        _id,
        qq: userqq,
        code,
        msg,
        token,
      } = await UserLogin({
        qq,
        avatar,
        nickname,
        email,
        weburl,
      })
      if (code) {
        props.login({ _id, qq: userqq, nickname, email, weburl, avatar })
        message.success(msg)
        storage.set('token', token)
        setLoginState(true)
      }
    }

    setIsLoging(false) // 加载完毕
  }

  // 自动登录
  const autoLogin = async () => {
    setIsLoging(true) // 加载开始
    let token = storage.get('token')
    if (token) {
      const { code, payload } = await UserAuthentication()
      if (code) {
        let { _id, qq, nickname, email, weburl, avatar } = payload
        setFormFields((prevState: any) => {
          return {
            ...prevState,
            qq,
            avatar,
            nickname,
            email,
            weburl,
          }
        })
        message.success('欢迎你！' + nickname)
        storage.set('token', token)
        props.login({ _id, qq, nickname, email, weburl, avatar })
        setLoginState(true)
        setIsLoging(false) // 加载完毕
        return
      }
    }
    storage.del('token')
    await UserLogout()
    setIsLoging(false) // 加载完毕
  }

  // 注销
  const logout = async () => {
    storage.del('token')
    setLoginState(false) //注销
    const { code, msg } = await UserLogout()
    if (code) {
      setFormFields({
        qq: '',
        nickname: '',
        email: '',
        avatar: '',
        weburl: '',
      })
      props.logout()
      message.success(msg)
    }
  }

  // 获取随机头像
  const getAvatar = async () => {
    const ret = (await GetRandomAvatar()) as any
    setFormFields((prevState: any) => {
      return {
        ...prevState,
        avatar: ret.imgurl,
      }
    })
  }

  // 提交留言
  const submit = async () => {
    if (comment && comment.length > 5) {
      const res: any = await InsertComment({
        secret,
        content: comment,
        replyId,
        at,
      })
      if (res.code) {
        message.success(`Hi ${formFields.nickname} 感谢你的留言！`)
        setComment('') // 清空文本框
        fetchComment() // 重新加载留言列表
        setReplyId('') // 清空回复对象
        setScrollY(0) // 重置移动位置
      }
    } else {
      message.warn('请写下您的评论! 不少于五个字哦~')
    }
  }

  // 回复留言
  const replyTo = async (comment: any, _id: string, scrollY: number) => {
    textArea.current?.focus()
    setReplyId(_id)
    setScrollY(scrollY)
    setAt(`@${comment.userinfo.nickname}`)
  }

  // 删除留言
  const deleteComment = async (commId: string, mainCommId?: string) => {
    const isDel = await DeleteComment(commId, mainCommId)
    if (isDel) {
      message.success('删除成功！')
      fetchComment(current, pagesize)
    }
  }

  // 分页
  const changePagination = (page: number, pageSize: number) => {
    setCurrent(page)
    setPagesize(pageSize)
    fetchComment(page - 1, pageSize)
  }

  // 每页条数
  const changePageSize = (current: number, pageSize: number) => {
    setCurrent(current)
    setPagesize(pageSize)
    fetchComment(current - 1, pageSize)
  }

  const { qq, nickname, email, weburl } = formFields

  return (
    <>
      <form id="comment-form" className="comment-form">
        {/* 用户数据 */}
        <div className="comment-wellcome">
          <div className="wellcome-inner" hidden={!loginState}>
            <h2>欢迎你 {nickname}</h2>
            <Button type="link" onClick={logout}>
              注销
            </Button>
          </div>
        </div>
        <div className="comment-header">
          <div className="user-avatar">
            <img
              className="avatar"
              src={formFields.avatar ? formFields.avatar : defaultAvatar}
            />
          </div>
          <div className="form-item-group">
            <div className="form-item">
              <div className="form-item-inner">
                <input
                  readOnly={loginState}
                  value={qq}
                  id="qq"
                  name="qq"
                  type="text"
                  placeholder="QQ号码可以获取头像和昵称"
                  onInput={handelInput}
                  onBlur={handelInputBlur}
                />
              </div>
            </div>
            <div className="form-item">
              <div className="form-item-inner">
                <input
                  // disabled={!isLoging}
                  readOnly={loginState}
                  value={nickname}
                  id="nickname"
                  name="nickname"
                  type="text"
                  placeholder="昵称"
                  onInput={handelInput}
                />
              </div>
              <p className="form-item-tips">
                提示:输入QQ号码可以直接获取您的信息
              </p>
            </div>
            <div className="form-item">
              <div className="form-item-inner">
                <input
                  // disabled={!isLoging}
                  readOnly={loginState}
                  value={email}
                  id="email"
                  name="email"
                  type="text"
                  placeholder="邮箱"
                  onInput={handelInput}
                />
              </div>
            </div>
            <div className="form-item">
              <div className="form-item-inner">
                <input
                  readOnly={loginState}
                  // disabled={!isLoging}
                  value={weburl}
                  id="weburl"
                  name="weburl"
                  type="text"
                  placeholder="网站(选填)"
                  onInput={handelInput}
                />
              </div>
            </div>
          </div>
        </div>
        {/* 回复框 */}
        <div className={`comment-editor ${secret ? 'secret' : ''}`}>
          <textarea
            ref={textArea}
            value={comment}
            name="content"
            id="content"
            placeholder={!secret ? placeholder : '开启悄悄话...'}
            onInput={handelTextAreaInput}
            required
          ></textarea>
        </div>
        {/* 功能区 */}
        <div className="form-footer">
          <div className="comment-emoji">
            <Emoji handelEmojiChose={handelEmojiChose} />
          </div>
          <div className="comment-secret">
            悄悄话 <Switch size="small" onChange={handelSwitchChange} />
          </div>
          <div className="comment-words">
            <span> {comment.length} </span>
            <span> / </span>
            <span> 字 </span>
          </div>
          <div className="comment-button-groups">
            <Button hidden={loginState} onClick={login} loading={isLoging}>
              登录
            </Button>
            <Button type="primary" hidden={!loginState} onClick={submit}>
              提交
            </Button>
          </div>
        </div>
      </form>
      {/* 留言列表 */}
      <List
        userinfo={props.userinfo}
        comments={comments}
        replyTo={replyTo}
        changePageSize={changePageSize}
        changePagination={changePagination}
        deleteComment={deleteComment}
        current={current}
        pagesize={pagesize}
        total={total}
      />
    </>
  )
}

export default form
